package com.sqx.modules.creation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.creation.dao.CreationCommentDao;
import com.sqx.modules.creation.dao.CreationGoodDao;
import com.sqx.modules.creation.dao.CreationReplyDao;
import com.sqx.modules.creation.entity.NCreationComment;
import com.sqx.modules.creation.entity.NCreationGood;
import com.sqx.modules.creation.entity.NCreationReply;
import com.sqx.modules.creation.entity.dto.AddCommentDto;
import com.sqx.modules.creation.entity.dto.AddCommentReplyDto;
import com.sqx.modules.creation.entity.vo.CommentReplyVo;
import com.sqx.modules.creation.entity.vo.GetCommentListVo;
import com.sqx.modules.creation.entity.vo.GetReplyListVo;
import com.sqx.modules.creation.entity.vo.SelCommentByIdVo;
import com.sqx.modules.creation.service.CreationCommentService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024年09月06日
 */
@Service
public class CreationCommentServiceImpl extends ServiceImpl<CreationCommentDao, NCreationComment> implements CreationCommentService {

    @Autowired
    private CreationCommentDao creationCommentDao;
    @Autowired
    private CreationReplyDao creationReplyDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CreationGoodDao creationGoodDao;

    @Override
    public Result addComment(Long userId, AddCommentDto addCommentDto) {
        NCreationComment creationComment = new NCreationComment();
        creationComment.setCreationId(addCommentDto.getCreationId());
        creationComment.setUserId(userId.intValue());
        creationComment.setCommentContent(addCommentDto.getCommentContent());
        creationComment.setCreateTime(new Date());
        creationCommentDao.insert(creationComment);
        return Result.success();
    }

    @Override
    public Result addCommentReply(Long userId, AddCommentReplyDto addCommentReplyDto) {
        NCreationReply creationReply = new NCreationReply();
        creationReply.setCreationCommentId(addCommentReplyDto.getCreationCommentId());
        creationReply.setUserId(userId.intValue());
        creationReply.setCreationId(addCommentReplyDto.getCreationId());
        creationReply.setReplyContent(addCommentReplyDto.getReplyContent());
        if (ObjectUtils.isNotEmpty(addCommentReplyDto.getParentId())){
            creationReply.setParentId(addCommentReplyDto.getParentId());
        }else {
            creationReply.setParentId(0);
        }
        creationReply.setCreateTime(new Date());
        creationReplyDao.insert(creationReply);
        return Result.success();
    }

    @Override
    public Result getCommentList(Long userId,Long creationId,Integer page,Integer limit) {
        Page<NCreationComment> creationCommentPage = new Page<>(ObjectUtils.isEmpty(page) ? 1 : page, ObjectUtils.isEmpty(limit) ? 10 : limit);
        LambdaQueryWrapper<NCreationComment> creationCommentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        creationCommentLambdaQueryWrapper.eq(NCreationComment::getCreationId, creationId);
        IPage<NCreationComment> commentIPage = creationCommentDao.selectPage(creationCommentPage, creationCommentLambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(commentIPage.getRecords())){
            //查所有的评论用户
            List<Integer> commentUserIds = commentIPage.getRecords().stream().map(NCreationComment::getUserId).collect(Collectors.toList());
            List<UserEntity> users = userDao.selectBatchIds(commentUserIds);
            HashMap<Long, UserEntity> map = new HashMap<>();
            for (UserEntity user : users) {
                map.put(user.getUserId(), user);
            }
            //todo 查询所有点赞的记录
            List<Integer> commentIds = commentIPage.getRecords().stream().map(NCreationComment::getCreationCommentId).collect(Collectors.toList());
            LambdaQueryWrapper<NCreationGood> creationCommentLikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            creationCommentLikeLambdaQueryWrapper.in(NCreationGood::getCommentId, commentIds);
            creationCommentLikeLambdaQueryWrapper.eq(NCreationGood::getUserId, userId);
            List<NCreationGood> creationCommentLikeList = creationGoodDao.selectList(creationCommentLikeLambdaQueryWrapper);
            HashMap<Integer, NCreationGood> creationCommentLikeHashMap = new HashMap<>();
            for (NCreationGood creationCommentLike : creationCommentLikeList) {
                creationCommentLikeHashMap.put(creationCommentLike.getCommentId(), creationCommentLike);
            }
            List<GetCommentListVo> commentListVos = commentIPage.getRecords().stream().map(o -> {
                GetCommentListVo getCommentListVo = BeanUtil.toBean(o, GetCommentListVo.class);
                getCommentListVo.setUserName(map.get(getCommentListVo.getUserId().longValue()).getUserName());
                getCommentListVo.setUserAvatar(map.get(getCommentListVo.getUserId().longValue()).getAvatar());
                getCommentListVo.setIsGood(ObjectUtils.isEmpty(creationCommentLikeHashMap.get(getCommentListVo.getCreationCommentId())) ? 0 : 1);
                //回复数
                LambdaQueryWrapper<NCreationReply> replyLambdaQueryWrapper = new LambdaQueryWrapper<>();
                replyLambdaQueryWrapper.eq(NCreationReply::getCreationCommentId, o.getCreationCommentId());
                getCommentListVo.setReplyNum(creationReplyDao.selectCount(replyLambdaQueryWrapper));
                return getCommentListVo;
            }).collect(Collectors.toList());



//            //判读当前评论是否点赞
//            //查询所有点赞的记录
//            List<Integer> commentIds = creationCommentList.stream().map(NCreationComment::getCreationCommentId).collect(Collectors.toList());
//            LambdaQueryWrapper<NCreationGood> creationCommentLikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            creationCommentLikeLambdaQueryWrapper.in(NCreationGood::getCommentId, commentIds);
//            creationCommentLikeLambdaQueryWrapper.eq(NCreationGood::getUserId, userId);
//            List<NCreationGood> creationCommentLikeList = creationGoodDao.selectList(creationCommentLikeLambdaQueryWrapper);
//            HashMap<Integer, NCreationGood> creationCommentLikeHashMap = new HashMap<>();
//            for (NCreationGood creationCommentLike : creationCommentLikeList) {
//                creationCommentLikeHashMap.put(creationCommentLike.getCommentId(), creationCommentLike);
//            }
//
//            for (GetCommentListVo getCommentListVo : getCommentListVos) {
//                getCommentListVo.setIsGood(ObjectUtils.isEmpty(creationCommentLikeHashMap.get(getCommentListVo.getCreationCommentId())) ? 0 : 1);
//                //查询评论的所有回复
//                LambdaQueryWrapper<NCreationReply> creationReplyLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                creationReplyLambdaQueryWrapper.eq(NCreationReply::getCreationCommentId, getCommentListVo.getCreationCommentId());
//                creationReplyLambdaQueryWrapper.orderByAsc(NCreationReply::getCreateTime);
//                List<NCreationReply> creationReplyList = creationReplyDao.selectList(creationReplyLambdaQueryWrapper);
//                if (ObjectUtils.isNotEmpty(creationReplyList)) {
//                    List<Integer> replyUserIds = creationReplyList.stream().map(NCreationReply::getUserId).collect(Collectors.toList());
//                    List<UserEntity> userEntities = userDao.selectBatchIds(replyUserIds);
//                    //回复的所有用户信息
//                    HashMap<Long, UserEntity> hashMap = new HashMap<>();
//                    for (UserEntity userEntity : userEntities) {
//                        hashMap.put(userEntity.getUserId(), userEntity);
//                    }
//                    //循环所有回复
//                    HashMap<Long, CommentReplyVo> replyVoHashMap = new HashMap<>();
//                    if (ObjectUtils.isNotEmpty(creationReplyList)){
//                        //判断用户当前评论是否点赞
//                        //查询所有点赞的记录
//                        List<Integer> replyIds = creationReplyList.stream().map(NCreationReply::getCreationReplyId).collect(Collectors.toList());
//                        LambdaQueryWrapper<NCreationGood> creationReplyLikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                        creationReplyLikeLambdaQueryWrapper.in(NCreationGood::getReplyId, replyIds);
//                        creationReplyLikeLambdaQueryWrapper.eq(NCreationGood::getUserId, userId);
//                        List<NCreationGood> creationReplyLikeList = creationGoodDao.selectList(creationReplyLikeLambdaQueryWrapper);
//                        HashMap<Integer, NCreationGood> creationReplyLikeHashMap = new HashMap<>();
//                        for (NCreationGood creationReplyLike : creationReplyLikeList) {
//                            creationReplyLikeHashMap.put(creationReplyLike.getReplyId(), creationReplyLike);
//                        }
//                        ArrayList<CommentReplyVo> commentReplyVos = new ArrayList<>();
//                        for (NCreationReply reply : creationReplyList) {
//                            CommentReplyVo commentReplyVo = BeanUtil.toBean(reply, CommentReplyVo.class);
//                            commentReplyVo.setUserName(hashMap.get(commentReplyVo.getUserId().longValue()).getUserName());
//                            commentReplyVo.setUserAvatar(hashMap.get(commentReplyVo.getUserId().longValue()).getAvatar());
//                            replyVoHashMap.put(commentReplyVo.getCreationReplyId().longValue(), commentReplyVo);
//                            commentReplyVo.setIsGood(ObjectUtils.isEmpty(creationReplyLikeHashMap.get(commentReplyVo.getCreationReplyId())) ? 0 : 1);
//                            commentReplyVos.add(commentReplyVo);
//                        }
//                        //设置被回复的用户头像和昵称
//                        for (CommentReplyVo commentReplyVo : commentReplyVos) {
//                            if (commentReplyVo.getParentId()!=0){
//                                commentReplyVo.setReplyUserName(replyVoHashMap.get(commentReplyVo.getParentId().longValue()).getUserName());
//                                commentReplyVo.setReplyUserAvatar(replyVoHashMap.get(commentReplyVo.getParentId().longValue()).getUserAvatar());
//                            }
//                        }
//                        getCommentListVo.setCommentReplyVos(commentReplyVos);
//                    }
//                }
//            }
            return Result.success().put("data",new PageUtils(commentListVos, Math.toIntExact(creationCommentPage.getTotal()), Math.toIntExact(creationCommentPage.getSize()), Math.toIntExact(creationCommentPage.getCurrent())));
        }
        return Result.success().put("data",new PageUtils(new ArrayList<>(), 0, 0, 0));
    }

    @Override
    public Result getReplyList(Long userId, Long commentId,Integer page,Integer limit) {
        //查询评论的所有回复
        Page<NCreationReply> creationReplyPage = new Page<>(ObjectUtils.isEmpty(page)?1:page, ObjectUtils.isEmpty(limit)?10:limit);
        LambdaQueryWrapper<NCreationReply> creationReplyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        creationReplyLambdaQueryWrapper.eq(NCreationReply::getCreationCommentId, commentId);
        creationReplyLambdaQueryWrapper.orderByAsc(NCreationReply::getCreateTime);
        IPage<NCreationReply> creationReplyIPage = creationReplyDao.selectPage(creationReplyPage, creationReplyLambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(creationReplyIPage.getRecords())) {
            List<Integer> replyUserIds = creationReplyIPage.getRecords().stream().map(NCreationReply::getUserId).collect(Collectors.toList());
            List<UserEntity> userEntities = userDao.selectBatchIds(replyUserIds);
            //回复的所有用户信息
            HashMap<Long, UserEntity> hashMap = new HashMap<>();
            for (UserEntity userEntity : userEntities) {
                hashMap.put(userEntity.getUserId(), userEntity);
            }
            //循环所有回复
            HashMap<Long, CommentReplyVo> replyVoHashMap = new HashMap<>();
            if (ObjectUtils.isNotEmpty(creationReplyIPage.getRecords())){
                //判断用户当前评论是否点赞
                //查询所有点赞的记录
                List<Integer> replyIds = creationReplyIPage.getRecords().stream().map(NCreationReply::getCreationReplyId).collect(Collectors.toList());
                LambdaQueryWrapper<NCreationGood> creationReplyLikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                creationReplyLikeLambdaQueryWrapper.in(NCreationGood::getReplyId, replyIds);
                creationReplyLikeLambdaQueryWrapper.eq(NCreationGood::getUserId, userId);
                List<NCreationGood> creationReplyLikeList = creationGoodDao.selectList(creationReplyLikeLambdaQueryWrapper);
                HashMap<Integer, NCreationGood> creationReplyLikeHashMap = new HashMap<>();
                for (NCreationGood creationReplyLike : creationReplyLikeList) {
                    creationReplyLikeHashMap.put(creationReplyLike.getReplyId(), creationReplyLike);
                }
                List<CommentReplyVo> replyVos = creationReplyIPage.getRecords().stream().map(o -> {
                    CommentReplyVo commentReplyVo = BeanUtil.toBean(o, CommentReplyVo.class);
                    commentReplyVo.setUserName(hashMap.get(commentReplyVo.getUserId().longValue()).getUserName());
                    commentReplyVo.setUserAvatar(hashMap.get(commentReplyVo.getUserId().longValue()).getAvatar());
                    replyVoHashMap.put(commentReplyVo.getCreationReplyId().longValue(), commentReplyVo);
                    commentReplyVo.setIsGood(ObjectUtils.isEmpty(creationReplyLikeHashMap.get(commentReplyVo.getCreationReplyId())) ? 0 : 1);
                    return commentReplyVo;
                }).collect(Collectors.toList());
                //设置被回复的用户头像和昵称
                for (CommentReplyVo commentReplyVo : replyVos) {
                    if (commentReplyVo.getParentId()!=0){
                        commentReplyVo.setReplyUserName(replyVoHashMap.get(commentReplyVo.getParentId().longValue()).getUserName());
                        commentReplyVo.setReplyUserAvatar(replyVoHashMap.get(commentReplyVo.getParentId().longValue()).getUserAvatar());
                    }
                }
                return Result.success().put("data",new PageUtils(replyVos, Math.toIntExact(creationReplyIPage.getTotal()), Math.toIntExact(creationReplyIPage.getSize()), Math.toIntExact(creationReplyIPage.getCurrent())));
            }
        }
        return Result.success().put("data", new PageUtils(new ArrayList<>(),0,0,0));
    }

    @Override
    public Result selCommentById(Integer commentId) {
        NCreationComment creationComment = baseMapper.selectById(commentId);
        SelCommentByIdVo selCommentByIdVo = BeanUtil.toBean(creationComment, SelCommentByIdVo.class);
        UserEntity user = userDao.selectById(creationComment.getUserId());
        selCommentByIdVo.setUserName(user.getUserName());
        selCommentByIdVo.setUserAvatar(user.getAvatar());
        return Result.success().put("data",selCommentByIdVo);
    }


}
